/*
 * @Author: 来自火星的码农 15122322+heyzhi@user.noreply.gitee.com
 * @Date: 2025-07-29 12:55:51
 * @LastEditors: 来自火星的码农 15122322+heyzhi@user.noreply.gitee.com
 * @LastEditTime: 2025-08-30 23:46:46
 * @FilePath: /server/workspace/src/base/timer.h
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * 
 * 
 */
#pragma once
#include<memory>
#include<functional>
#include"mutex.h"
#include<set>
#include<vector>
namespace Yizhi {
    class TimerManager;
    class Timer:public std::enable_shared_from_this<Timer>{
        friend class TimerManager;
        
        public:
        typedef RWMutex RWMutexType;
        typedef std::shared_ptr<Timer> ptr;
        typedef std::function<void()> CallbackType;

        bool refush();

        bool cancel();

        bool reset(uint64_t ms,bool fromnow);


        private:
        Timer(uint64_t ms,bool recurring,TimerManager* manager,CallbackType cb);


        Timer(uint64_t next);
        private:

        struct Comparator
        {
            bool operator()(const Timer::ptr& lhs,const Timer::ptr& rhs) const;
        };
        

        //currentms+m_ms,定时器声明时的时间+定时器的执行时间，
        uint64_t m_next=0;

        //执行周期，多久执行一次任务
        uint64_t m_ms=0;

         //是否循环运行时间
         bool m_recurring=false;

        //回调函数
        CallbackType m_cb=nullptr;

        TimerManager * m_manager=nullptr;
    };


    class TimerManager{
        friend class Timer;
        public:
        typedef RWMutex RWMutexType;
        typedef std::function<void()> CallbackType;

        Timer::ptr addTimer(uint64_t ms,CallbackType cb,bool recurring=false);
        Timer::ptr addCondtionTimer(uint64_t ms,CallbackType cb,std::weak_ptr<void>con_ptr,bool recurring=false);
        
        uint64_t GetNextTimer();

        void listExpiredCb(std::vector<std::function<void()>> &cbs);
        
        TimerManager();
        virtual ~TimerManager();
        bool hasNext();
        protected:

        virtual void onTimerInsertFront()=0;
        void addTimer(Timer::ptr val,RWMutexType::WriteLock &wlock);

        
        private:
        RWMutexType m_mutex;
        bool m_tickle=false;
        std::set<Timer::ptr, Timer::Comparator> m_timers;
        
    };

  


}